package yt.kpool.activity.setting;

import android.Manifest;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.zxing.WriterException;
import com.yzq.zxinglibrary.encode.CodeCreator;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.activity.personal.FastLookUserDetailActivity;
import yt.kpool.base.BaseApplication;
import yt.kpool.bean.BaseBean;
import yt.kpool.bean.ChildAccountAPIKeyBean;
import yt.kpool.bean.ChildAccountBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.SPUtil;
import yt.kpool.util.TitleControl;
import yt.kpool.util.ToastUtil;
import yt.kpool.view.AutoTextView;
import yt.kpool.view.dialog.AddGroupDialog;
import yt.kpool.view.dialog.ContentDialog;
import yt.kpool.view.dialog.EditDialog;
import yt.kpool.view.dialog.LoadingDialog;
import yt.kpool.view.pop.SavePopupWindow;

public class OnlyReadActivity extends AppCompatActivity {
    private LoadingDialog loadingDialog;
    @BindView(R.id.iv_code)
    ImageView iv_code;
    @BindView(R.id.tv_link)
    TextView tv_link;

    @BindView(R.id.tv_remark)
    TextView tv_remark;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_apikey)
    TextView tv_apikey;
    @BindView(R.id.tv_amountname)
    TextView tv_amountname;

    private String link = "";


    public static void start(Activity mactivity, String ChildAccountID, String Remark, String CreateTime, String APIKey, String Urls, String accountName, String ID) {
        Intent intent = new Intent(mactivity, OnlyReadActivity.class);
        intent.putExtra("ChildAccountID", ChildAccountID);
        intent.putExtra("Remark", Remark);
        intent.putExtra("APIKey", APIKey);
        intent.putExtra("CreateTime", CreateTime);
        intent.putExtra("Url", Urls);
        intent.putExtra("accountName", accountName);
        intent.putExtra("ID", ID);
        mactivity.startActivityForResult(intent, 32);
    }

    public String getChildAccountID() {
        return getIntent().getStringExtra("ChildAccountID");
    }

    public String getRemark() {
        return getIntent().getStringExtra("Remark");
    }

    public String getAPIKey() {
        return getIntent().getStringExtra("APIKey");
    }

    public String getCreateTime() {
        return getIntent().getStringExtra("CreateTime");
    }

    public String getUrl() {
        return getIntent().getStringExtra("Url");
    }

    public String getAccountName() {
        return getIntent().getStringExtra("accountName");
    }

    public String getID() {
        return getIntent().getStringExtra("ID");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_only_read);
        ButterKnife.bind(this);
        initTitle();
        initView();


        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 70);
            Log.i("-->", "读写权限申请");
        }


    }

    private void initView() {
        link = getUrl();
        tv_remark.setText(getRemark());
        tv_time.setText(getCreateTime());
        tv_apikey.setText(getAPIKey());
        tv_link.setText(getUrl());
        tv_amountname.setText("挖矿账户 " + getAccountName() + " 的只读页面链接");
        getMipmap();
    }


    /**
     * 删除
     */
    private void delete() {
        if (NetWorkUtil.check(this)) {


            loadingDialog.show();
            NetHelperNew.DeleteChildAccountAPIKey(getID(), new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "删除APIKey：" + data);
                    BaseBean baseBean = MyGson.getInstance().fromJson(data, BaseBean.class);
                    if (baseBean.getType() == 1) {


                        ToastUtil.showToast(getApplicationContext(), baseBean.getContent());
                        setResult(26, getIntent());
                        finish();
                    } else {
                        ToastUtil.showToast(getApplicationContext(), baseBean.getContent());
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);

                    loadingDialog.dismiss();
                    ToastUtil.showToast(getApplicationContext(), msg);
                }
            });


        }

    }

    /**\
     * 修改备注
     */
    private void editRemark(String remark) {
        if (NetWorkUtil.check(this)) {


            loadingDialog.show();
            NetHelperNew.UpdateChildAccounKeyRemark(getID(),remark, new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "修改APIKey备注：" + data);
                    BaseBean baseBean = MyGson.getInstance().fromJson(data, BaseBean.class);
                    if (baseBean.getType() == 1) {


                        ToastUtil.showToast(getApplicationContext(), baseBean.getContent());
                        setResult(26, getIntent());
                        finish();
                    } else {
                        ToastUtil.showToast(getApplicationContext(), baseBean.getContent());
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);

                    loadingDialog.dismiss();
                    ToastUtil.showToast(getApplicationContext(), msg);
                }
            });


        }

    }

    /**
     * 生成apikey
     */
    private void upData() {
        if (NetWorkUtil.check(this)) {


            loadingDialog.show();
            NetHelperNew.UpdateChildAccountAPIKey(getChildAccountID(), getRemark(), new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "生成APIKey：" + data);
                    ChildAccountAPIKeyBean childAccountBean = MyGson.getInstance().fromJson(data, ChildAccountAPIKeyBean.class);
                    if (childAccountBean.getType() == 1) {
                        ChildAccountAPIKeyBean.DataBean data1 = childAccountBean.getData();
                        tv_remark.setText(data1.getRemark());
                        tv_time.setText(data1.getCreateTime());
                        tv_apikey.setText(data1.getAPIKey());
                        tv_link.setText(data1.getUrl());
                        link = data1.getUrl();
                        getMipmap();
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);

                    loadingDialog.dismiss();
                    ToastUtil.showToast(getApplicationContext(), msg);
                }
            });


        }

    }

    private void getMipmap() {
        try {
            /*
             * contentEtString：字符串内容
             * w：图片的宽
             * h：图片的高
             * logo：不需要logo的话直接传null
             * */

            Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
            final Bitmap bitmap = CodeCreator.createQRCode(link, 400, 400, logo);
            iv_code.setImageBitmap(bitmap);

            iv_code.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    SavePopupWindow savePopupWindow = new SavePopupWindow(OnlyReadActivity.this, bitmap);
                    savePopupWindow.showAtLocation(iv_code, Gravity.BOTTOM, 0, 20);
                    return false;
                }
            });
        } catch (WriterException e) {
            e.printStackTrace();
        }

    }

    @OnClick({R.id.tv_update, R.id.btn_copy, R.id.iv_editremark})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_update:
                //更新
                upData();
                break;
            case R.id.iv_editremark:
                //修改备注

                new EditDialog(OnlyReadActivity.this, "修改备注",getRemark(),"请输入备注", new EditDialog.OnSuccessListener() {

                    @Override
                    public void getResult(String editstring) {

                        editRemark(editstring);
                    }
                }).show();
                break;

            case R.id.btn_copy:
                //复制
                ClipboardManager cmb = (ClipboardManager) this.getSystemService(CLIPBOARD_SERVICE);
                cmb.setText(link);
                ToastUtil.showToast(this, "链接已复制到剪贴板");
                break;


        }
    }

    private void initTitle() {
        TitleControl titleControl = new TitleControl(this);
        titleControl.setTitle("只读页面链接");

        titleControl.setRightText("删除", new TitleControl.OnClickRight() {
            @Override
            public void onRight() {
                new ContentDialog(OnlyReadActivity.this, "确定要删除 " + getRemark() + " 吗?", "提示", new ContentDialog.OnSuccessListener() {
                    @Override
                    public void sure() {

                        delete();
                    }
                }).show();
            }
        });
        loadingDialog = new LoadingDialog(this, 0);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == 70) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {


            } else {

                new AlertDialog.Builder(this)
                        .setTitle("权限申请")
                        .setMessage("在设置-应用-" + getString(R.string.app_name) + "-权限中启动读写权限，以正常使用保存图片功能")

                        .setNegativeButton("取消", null)
                        .show();
            }
        }

    }
}
